package com.ninja.config;

import com.ninja.pojo.config.Configuration;
import com.ninja.pojo.config.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElment = document.getRootElement();
        List<Element> elementList = rootElment.selectNodes("//select|//insert|//update|//delete");

        String nameSpace = rootElment.attributeValue("namespace");
        elementList.forEach(element -> {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sqlStr = element.getTextTrim();
            String nodeName = element.getName().toUpperCase();

            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setSql(sqlStr);
            mappedStatement.setSqlCommandType(nodeName);
            String key = nameSpace+"."+id;

            configuration.getMappedStatementMap().put(key,mappedStatement);

        });

    }
}
